#ifndef TCPMANAGER_H
#define TCPMANAGER_H

#include <QObject>
#include <QTcpServer>
#include <QTcpSocket>

enum INFOTYPE
{
    NewClientType,
    FilePacketType,
    MessagePacketType
};

struct Stu_Head
{
    int     dataSize;
    int     infoType;
};

struct NewClient
{
    int     dataSize;
    int     infoType = NewClientType;
    QString ip;

    friend QDataStream &operator<<(QDataStream &out,const NewClient &packet)
    {
        out << packet.dataSize << packet.infoType << packet.ip;
        return out;
    }

    friend QDataStream &operator>>(QDataStream &in,NewClient &packet)
    {
        in >> packet.dataSize >> packet.infoType >> packet.ip;
        return in;
    }
};

struct FilePacket {
    int     dataSize;
    int     infoType = FilePacketType;
    QString sourceAddress;
    QString targetAddress;  // 目标地址
    QString fileName;       // 文件名
    QString fileType;       // 文件类型
    QByteArray fileData;    // 文件数据

    // 序列化操作（发送时）
    friend QDataStream &operator<<(QDataStream &out, const FilePacket &packet) {
        out << packet.dataSize << packet.infoType << packet.sourceAddress << packet.targetAddress << packet.fileName << packet.fileType << packet.fileData;
        return out;
    }

    // 反序列化操作（接收时）
    friend QDataStream &operator>>(QDataStream &in, FilePacket &packet) {
        in >> packet.dataSize >> packet.infoType >> packet.sourceAddress >> packet.targetAddress >> packet.fileName >> packet.fileType >> packet.fileData;
        return in;
    }
};

struct MessagePacket {
    int     dataSize;
    int     infoType = MessagePacketType;
    QString sourceAddress;
    QString targetAddress;      // 目标地址
    QString messageData;        // 消息内容

    // 序列化操作（发送时）
    friend QDataStream &operator<<(QDataStream &out, const MessagePacket &packet) {
        out << packet.dataSize << packet.infoType << packet.sourceAddress << packet.targetAddress << packet.messageData;
        return out;
    }

    // 反序列化操作（接收时）
    friend QDataStream &operator>>(QDataStream &in, MessagePacket &packet) {
        in >> packet.dataSize >> packet.infoType >> packet.sourceAddress >> packet.targetAddress >> packet.messageData;
        return in;
    }
};

class TcpManager : public QObject
{
    Q_OBJECT
public:
    explicit TcpManager(QObject *parent = nullptr);

private:
    void processData(QByteArray &msgData,int type);
    void noticeNewClient(NewClient &newClient);
    void cogradientClinet(QString targetIP,NewClient &newClient);

public slots:
    void onReadyRead(QTcpSocket* tcpSocket);
    void onNewConnection();
    void slot_DisConnected(QTcpSocket* tcpSocket);
signals:

private:
    QTcpServer* m_TcpServer;
    QMap<QString,QTcpSocket*> m_TcpSockets;
    QByteArray m_Buffer;
};

#endif // TCPMANAGER_H
